package company.maestro;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.graphics.Color;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.Spanned;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TableRow;

public class SessionMenuAndroidActivity extends Activity implements OnClickListener{

	private enum ImageButtonPosition {topLeft, topMiddle, topRight, 
						   		 	  middleLeft, middleMiddle, middleRight,
						   		 	  bottomLeft, bottomMiddle, bottomRight};
						   		 	  
	private static int counter = 1;
	
	//Will be used to access the Parent TableLayout
	private ViewGroup viewGroup = null;
	
	//Will be used to access the last view clicked by the User
	private View lastViewClicked;
	
	//Will be used to dynamically add a new TableRow of either Buttons or EditTexts to the 
	//TableLayout
	private TableRow addTableRowButton = null;
	private TableRow addTableRowEditText = null;
	
	//Will be used to dynamically add a new Button or EditText to the TableLayout
	private ImageButton addImageButton = null;
	private EditText addEditText = null;
	
	
	private  Button addButton = null;
	
	//Different Counters needed to dynamically add Views to the TableLayou
	private int buttonInRow = 0;
	private int buttonCounter = 0;
	private int buttonTotalCounter = 0;
	
	//Different upperLimits for views in TableRows and the TableLayou
	private int maxViewInARow = 3;
	private int maxViewInATable = 9;
	private int tableRowOffSet = 1;
	private int tableRowId = 1;
	
	/**
	 * Add for the Database
	 * */
	private SQLiteDatabase mDb;
	private Cursor mCursor = null;
	
	
	private SessionButtonDBAdapter mSessionButtonDBAdapter;
	
	/**
	 * First function called to initialize the activity
	 * */
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
        setContentView(R.layout.table);       
        viewGroup = (ViewGroup)findViewById(R.id.table);
        addButton = (Button)findViewById(R.id.addButton);
        addButton.setOnClickListener(this); 
        mSessionButtonDBAdapter = new SessionButtonDBAdapter(this);
        mSessionButtonDBAdapter.open();
        initializeActivityScreen();
	}
	
	
	public void initializeActivityScreen() {
		mCursor = mSessionButtonDBAdapter.getAllSessionButtonsCursor(); 
		if(mCursor.getCount() != 0){
			while(mCursor.moveToNext()){
				addViewsToLayout();
			}
		}
	}
	     
	public void onClick(View arg0) {
		addItemToDatabase();
		addItemToLayout();
	}
	
	public void addItemToDatabase() {
		SessionButton addSessionButton = new SessionButton("class " + counter , counter);
		mSessionButtonDBAdapter.insertSession(addSessionButton);
		counter++;
	}
	
	public void addItemToLayout(){
		mCursor = mSessionButtonDBAdapter.getAllSessionButtonsCursor();
		mCursor.moveToLast();
		addViewsToLayout();
	}
		
	public void addViewsToLayout() {
		mSessionButtonDBAdapter.getAllSessionButtonsCursor(); 
		ImageButton addImageButton = new ImageButton(this);
		addImageButton.setImageResource(R.drawable.ic_folder);
		addImageButton.setBackgroundColor(Color.argb(0, 0, 0, 0));
		addImageButton.setOnClickListener(popupMenu);
        registerForContextMenu(addImageButton);
		EditText addEditText = new EditText(this);
		addEditText.setText(mCursor.getString(mCursor.getColumnIndex(SessionButtonDBAdapter.KEY_SESSION_NAME)));
		addEditText.setBackgroundColor(Color.argb(0, 0, 0, 0));
		viewGroup.addView(addImageButton);
		viewGroup.addView(addEditText);		
	}


	/**
	 * When the User presses the "Click To Add More Sessions
	 * button, the click event will be handle
	 * by the onClick Listener
	 * */
	/*
	public void onClick(View v) {
		
		String[] columns = new String[] {MyDBHelper.KEY_ID, MyDBHelper.EDIT_TEXT_LABEL, MyDBHelper.IMAGE_BUTTON_POSITION};
		//String selection = MyDBHelper.IMAGE_BUTTON_POSITION+ " = ?";
		//String[] args = new String[] {"10"};
		try {
			mCursor = mDb.query(MyDBHelper.TABLE_NAME, columns, null, null, null, null, null);
			mCursor.moveToFirst();
		}
		catch(SQLiteException err){
			err.printStackTrace();
		}
		
		viewGroup = (ViewGroup) findViewById(R.id.table);
		TableRow tableRowArray[] = new TableRow[viewGroup.getChildCount()-1];
		 
		 //Counter will be used when user
		 //add more views than the maxViewInTable limit
		 //because the user has deleted other buttons
		 int tableRowArrayCounter = 0;
			
	     //Should have at least 1 row in the TableLayout
		 //because of the Add More Sessions Button
		 int numRows = viewGroup.getChildCount();
	     
		 //The heart of adding buttons to TableLayout
	      if(buttonCounter < maxViewInATable){
	    	  
	        //If there is at least 1 TableRow of classes
	    	//Get the TableRow of the Butotn Clicked on
	    	//Get the TableRow of the EditText below
	    	//The Button that was clicked on.
	    	if( numRows > tableRowOffSet){
	            addTableRowButton = (TableRow) viewGroup.getChildAt(viewGroup.getChildCount() - 2 );
	            addTableRowEditText = (TableRow) viewGroup.getChildAt(viewGroup.getChildCount() - tableRowOffSet);
	            buttonInRow = addTableRowButton.getChildCount();         
	        }

	    	//If A TableRow of Button and TableRow of EditText
	    	//need to be created.
	        if( numRows == tableRowOffSet || buttonInRow == maxViewInARow ){
	            addTableRowButton = new TableRow( this );
	            addTableRowButton.setId(tableRowId);
	            addTableRowButton.setGravity(Gravity.CENTER_HORIZONTAL);
	            addTableRowButton.setPadding(0, 0, 0, 0);
	            viewGroup.addView( addTableRowButton );
	            tableRowId++;
	            
	            addTableRowEditText = new TableRow(this);
	            addTableRowEditText.setId(tableRowId);
	            addTableRowEditText.setGravity(Gravity.CENTER_HORIZONTAL);
	            addTableRowEditText.setPadding(10, 0, 10, 10);
	            viewGroup.addView(addTableRowEditText);
	            tableRowId++;
	            buttonInRow = 0;
	        }
	        
	        //If There is space available in the TableRow for
	        //Another Button and the total number of buttons
	        //hasn't exceeded the maxViewInATable limit
	        //add new Button and a new EditText below it
	        if( buttonInRow < maxViewInARow  && buttonTotalCounter < maxViewInATable){
	        	addImageButton = new ImageButton( this );
	            addImageButton.setId(buttonInRow);
	            addImageButton.setImageResource(R.drawable.ic_folder);
	            addImageButton.setBackgroundColor(Color.argb(0, 0, 0, 0));
	            addImageButton.setOnClickListener(popupMenu);
	            registerForContextMenu(addImageButton);
	            addTableRowButton.addView(addImageButton);
	            int idTest;
	            try{
	            	idTest = mCursor.getInt(2);
	            }
	            catch(Exception err) {
	            	err.printStackTrace();
	            	idTest = 2342;
	            }
	            addEditText = new EditText(this);
	            addEditText.setText("boobs" + idTest);
	            addEditText.setBackgroundColor(Color.argb(0, 0, 0, 0));
	            addTableRowEditText.addView(addEditText);
	            buttonInRow++;
	            buttonCounter++;
	            buttonTotalCounter++;
	        }
	        
	        //If the new Button has Exceeded the maxViewInATable value
	        //We need to make sure to add the Button and 
	        //the Edit to the correct TableRow.  
	        //The configuration of TableLayout can get mess up easily if
	        //We don't do some basic checks
	        else if(buttonTotalCounter >= maxViewInATable){
	        	//Get all the Rows in the the table except the top button
	    		while(tableRowArrayCounter < tableRowArray.length) {
	    				tableRowArray[tableRowArrayCounter] = (TableRow)viewGroup.getChildAt(tableRowArrayCounter+1);
	    				tableRowArrayCounter++;
	    			}
	    		//Reset Counter
	    		tableRowArrayCounter = 0;
	    		while(tableRowArrayCounter < tableRowArray.length){
	    			if(tableRowArray[tableRowArrayCounter].getChildCount() != maxViewInARow){
	    				addImageButton = new ImageButton( this );
	    				addImageButton.setBackgroundColor(Color.argb(0, 0, 0, 0));
	    	            addImageButton.setImageResource(R.drawable.ic_folder);
	    	            addImageButton.setId(buttonInRow);
	    	            addImageButton.setOnClickListener(popupMenu);
	    	            registerForContextMenu(addImageButton);
	    	            tableRowArray[tableRowArrayCounter].addView(addImageButton);
	    	            
	    	            addEditText = new EditText(this);
	    	            addEditText.setText("Class " + buttonTotalCounter);
	    	            addEditText.setBackgroundColor(Color.argb(0, 0, 0, 0));
	    	            tableRowArray[tableRowArrayCounter+1].addView(addEditText);
	    	            buttonInRow++;
	    	            buttonCounter++;
	    	            buttonTotalCounter++;
	    	            break;
	    			}
	    			tableRowArrayCounter++;
	    		}
	        }
	    }
	}
	*/
	
	/**
	 * OnClickListener for longClicks on the Button/Class Folder Icons 
	 ***/
	View.OnClickListener popupMenu = new View.OnClickListener() {		
		public void onClick(View v) {
			//This call the function to create the contextMenu to pop-open
			openContextMenu(v);
		}
	};
		
	/**
	 * This fuction creates the context menu
	 **/
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		lastViewClicked = v;
		
		getMenuInflater().inflate(R.menu.contextmenu, menu);
		menu.setHeaderTitle("Choose An Option");
	}
	
	
	/**
	 * This is a function that will perform the actions
	 * for the contextmenu item that we selected
	 * Always return true at the end of handle an event
	 * so the system consumes it!!!!!!!!!!!
	 **/
	@Override
	public boolean onContextItemSelected(MenuItem item){
		
		int viewIndex;
		int tableRowIndex;
		TableRow tableRowButtonLastTouched = null;
		TableRow tableRowEditTextModify = null;
		EditText editTextModify = null;
		switch(item.getItemId()) {/*
		case R.id.menu_save:
			
			//Initialize the local variables
			viewIndex = lastViewClicked.getId();
			tableRowButtonLastTouched = (TableRow)lastViewClicked.getParent();
			tableRowIndex = tableRowButtonLastTouched.getId();
			tableRowEditTextModify = (TableRow)viewGroup.getChildAt(tableRowIndex+1);
			editTextModify = (EditText)tableRowEditTextModify.getChildAt(viewIndex);
			
			//lock the EditText
			editTextModify.setBackgroundColor(Color.argb(0, 0, 0, 0));
			editTextModify.setEnabled(false);
			editTextModify.setClickable(false);
			editTextModify.setLongClickable(false);
			editTextModify.setFocusableInTouchMode(false);
			//Take from the internet at
			//http://thedevelopersinfo.com/2009/11/15/making-not-editable-edittext-in-android/
			editTextModify.setFilters(new InputFilter[] { new InputFilter() {				
				public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
				            return source.length() < 1 ? dest.subSequence(dstart, dend) : "";
				}}});

			return true;
		case R.id.menu_edit:
			
			//Initialize local variables
			viewIndex = lastViewClicked.getId();
			tableRowButtonLastTouched = (TableRow)lastViewClicked.getParent();
			tableRowIndex = tableRowButtonLastTouched.getId();
			tableRowEditTextModify = (TableRow)viewGroup.getChildAt(tableRowIndex+1);
			editTextModify = (EditText)tableRowEditTextModify.getChildAt(viewIndex);
			
			//Unlock the EditText
			editTextModify.setBackgroundColor(Color.argb(100, 0, 100, 100));
			editTextModify.setEnabled(true);
			editTextModify.setClickable(true);
			editTextModify.setLongClickable(true);
			editTextModify.setFocusableInTouchMode(true);
			
			//Take from the internet at
			//http://thedevelopersinfo.com/2009/11/15/making-not-editable-edittext-in-android/
			editTextModify.setFilters(new InputFilter[] { new InputFilter() {
				public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
				                    return null;
				}}});

			return true;*/
		case R.id.menu_delete:
			//Delete a single button and the editText below it
			TableRow tableRowArray[] = new TableRow[viewGroup.getChildCount()-1];
			int rightOfDeletedButtonCounter = 0;
			ImageButton imageButtonMoved = null;
			EditText editTextBeingMoved = null;
			
			//Initialize local variables
			viewIndex = lastViewClicked.getId();
			tableRowButtonLastTouched = (TableRow)lastViewClicked.getParent();
			tableRowIndex = tableRowButtonLastTouched.getId();
			tableRowEditTextModify = (TableRow)viewGroup.getChildAt(tableRowIndex+1);
			
			tableRowButtonLastTouched.removeViewAt(viewIndex);
			tableRowEditTextModify.removeViewAt(viewIndex);
			
			//Reset Ids in the row
			ImageButton[] rightOfDeletedButton = new ImageButton[tableRowButtonLastTouched.getChildCount()-viewIndex];
			EditText[] rightOfDeletedEditText = new EditText[tableRowButtonLastTouched.getChildCount()-viewIndex];
			while(rightOfDeletedButtonCounter < rightOfDeletedButton.length){
				rightOfDeletedButton[rightOfDeletedButtonCounter] = (ImageButton)tableRowButtonLastTouched.getChildAt(viewIndex);
				rightOfDeletedButton[rightOfDeletedButtonCounter].setId(rightOfDeletedButton[rightOfDeletedButtonCounter].getId()-1);
				
				rightOfDeletedEditText[rightOfDeletedButtonCounter] = (EditText)tableRowEditTextModify.getChildAt(viewIndex);
				rightOfDeletedEditText[rightOfDeletedButtonCounter].setId(rightOfDeletedEditText[rightOfDeletedButtonCounter].getId()-1);
				
				rightOfDeletedButtonCounter++;
				viewIndex++;
			}
			
			//Reconfigure layout
			int tableRowArrayCounter = 0;
			int viewInARowCounter = 0;
			
			//Get all the Rows in the the table except the top button
			while(tableRowArrayCounter < tableRowArray.length) {
				tableRowArray[tableRowArrayCounter] = (TableRow)viewGroup.getChildAt(tableRowArrayCounter+1);
				tableRowArrayCounter++;
			}
			
			//reset tableRowArrayCounter
			tableRowArrayCounter = 0;
			while(tableRowArrayCounter < tableRowArray.length){
				
				//Do not try to restructure the the layout if there is 
				//only 1 row of button\class folder icon
				if(tableRowArrayCounter < 2){
					tableRowArrayCounter++;
					continue;
				}
				
				//If the TableRow, two rows up from the current row isn't full
				//move the button\class folder at the zero index of the current row
				//and add it to the the TableRow, two rows up.
				else if(tableRowArray[tableRowArrayCounter-2].getChildCount() != maxViewInARow){
					//reset viewInARowCounter
					viewInARowCounter = 0;
					while(viewInARowCounter < tableRowArray[tableRowArrayCounter].getChildCount()){
						//If the TableRow above,now has, the maxViewInARow break out of the loop
						if(tableRowArray[tableRowArrayCounter-2].getChildCount() == maxViewInARow){
							break;
						}
						else
						{
							imageButtonMoved = (ImageButton)tableRowArray[tableRowArrayCounter].getChildAt(0);
							ImageButton addImageButton = new ImageButton(this);
							addImageButton.setImageResource(R.drawable.ic_folder);
							addImageButton.setBackgroundColor(Color.argb(0, 0, 0, 0));
							addImageButton.setId(maxViewInARow-1);
					        addImageButton.setOnClickListener(popupMenu);
					        registerForContextMenu(addImageButton);
					        tableRowArray[tableRowArrayCounter-2].addView(addImageButton);
					        tableRowArray[tableRowArrayCounter].removeViewAt(0);
					        
					        editTextBeingMoved = (EditText)tableRowArray[tableRowArrayCounter+1].getChildAt(0);
					        EditText addEditText = new EditText(this);
					        addEditText.setText(editTextBeingMoved.getText());
				            addEditText.setBackgroundColor(Color.argb(0, 0, 0, 0));
				            tableRowArray[tableRowArrayCounter-1].addView(addEditText, 120 ,100);
				            tableRowArray[tableRowArrayCounter+1].removeViewAt(0);
				           
						}
						viewInARowCounter++;
					}
					
				}
				tableRowArrayCounter++;
			}
			--buttonCounter;		
			return true;
			
		case R.id.menu_cancel:
			return true;
			
		case R.id.menu_delete_all:
			int sessionButtonTotal = 0;
			Cursor mDeleteCursor = mSessionButtonDBAdapter.getAllSessionButtonsCursor();
			while(mDeleteCursor.moveToNext()){
				mSessionButtonDBAdapter.removeSessionButton(mDeleteCursor.getColumnIndex(SessionButtonDBAdapter.KEY_ID));
			}
			/*
			while(sessionButtonTotal < mSessionButtonDBAdapter.getAllSessionButtonsCursor().getCount()){
				mSessionButtonDBAdapter.removeSessionButton(mSessionButtonDBAdapter.getAllSessionButtonsCursor().getColumnIndex(SessionButtonDBAdapter.KEY_ID));
				sessionButtonTotal++;
			}*/
			viewGroup.removeAllViews();
			viewGroup.addView(addButton);
			counter = 0;
			return true;
		}
		
		return super.onContextItemSelected(item);
	}


}
